package com.Final.hj;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.Toast;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {

    //注册按钮
    private Button registerBtn, imageRe, imageJe, toLogin;
    private ImageView selectImgBtn;

    private LinearLayout imagebtn1, imagebtn2,imagebtn3, imagebtn4,
            imagebtn5, imagebtn6, imagebtn7, imagebtn8,
            imagebtn9;

    //两个单选框
    private RadioButton type_cous, type_boss, gender_boy, gender_girl;
    private boolean type_flag = true; //true---普通用户 false----商家
    private boolean gender_flag = true; //true---男 false----女

    private LinearLayout[] lineData;


    private EditText uname;
    private EditText paw;
    private EditText email;

    private String un;
    private String pa;
    private String em;
    private String gender;
    private String type;
    private String hImgId;
    //图片集合
    private int [] imageList = {
            R.drawable.one, R.drawable.two, R.drawable.three,
            R.drawable.four, R.drawable.five, R.drawable.six,
            R.drawable.sevent, R.drawable.eight, R.drawable.nine
    };

    //默认图片
    private int selectImage = R.drawable.init_h_img;
    private int selectNum = -1;//选择图片的索引


    protected void onCreate(@Nullable Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rgister_main);
        //初始化变量
        initView();
    }

    public void initView(){

        registerBtn = (Button) findViewById(R.id.register_btn);
        selectImgBtn = (ImageView) findViewById(R.id.image_H);
        toLogin = (Button) findViewById(R.id.register_to_login);
        type_cous = (RadioButton) findViewById(R.id.type_cous);
        type_boss= (RadioButton) findViewById(R.id.type_boss);
        gender_boy= (RadioButton) findViewById(R.id.gender_boy);
        gender_girl= (RadioButton) findViewById(R.id.gender_girl);


        //默认普通用户 男
        type_cous.setChecked(true);
        gender_boy.setChecked(true);

        //文本框
        uname = (EditText) findViewById(R.id.register_edit_uname);
        paw = (EditText) findViewById(R.id.register_edit_paw);
        email = (EditText) findViewById(R.id.register_edit_email);

        //注册点击事件
        registerBtn.setOnClickListener(this);
        toLogin.setOnClickListener(this);
        selectImgBtn.setOnClickListener(this);
        //单选框
        type_cous.setOnClickListener(this);
        type_boss.setOnClickListener(this);
        gender_boy.setOnClickListener(this);
        gender_girl.setOnClickListener(this);
    }

    //初始化弹窗变量
    public void initSelectView(View view){
        imagebtn1 = (LinearLayout) view.findViewById(R.id.image_one);
        imagebtn2 = (LinearLayout) view.findViewById(R.id.image_two);
        imagebtn3 = (LinearLayout) view.findViewById(R.id.image_three);
        imagebtn4 = (LinearLayout) view.findViewById(R.id.image_four);
        imagebtn5 = (LinearLayout) view.findViewById(R.id.image_five);
        imagebtn6 = (LinearLayout) view.findViewById(R.id.image_six);
        imagebtn7 = (LinearLayout) view.findViewById(R.id.image_seven);
        imagebtn8 = (LinearLayout) view.findViewById(R.id.image_eight);
        imagebtn9 = (LinearLayout) view.findViewById(R.id.image_nine);

        imageRe = (Button) view.findViewById(R.id.image_solve);
        imageJe = (Button) view.findViewById(R.id.image_reject);

        imagebtn1.setOnClickListener(this);
        imagebtn2.setOnClickListener(this);
        imagebtn3.setOnClickListener(this);
        imagebtn4.setOnClickListener(this);
        imagebtn5.setOnClickListener(this);
        imagebtn6.setOnClickListener(this);
        imagebtn7.setOnClickListener(this);
        imagebtn8.setOnClickListener(this);
        imagebtn9.setOnClickListener(this);

        lineData = new LinearLayout[] {imagebtn1, imagebtn2,imagebtn3, imagebtn4,
                imagebtn5, imagebtn6, imagebtn7, imagebtn8,
                imagebtn9};
        lineData[0].setBackgroundColor(Color.parseColor("#f5f3e8"));

    }

    @Override
    public void onClick(View v){
        switch (v.getId()){
            case R.id.register_btn:
                //调用方法
                sendRegisterHttp();
                break;
            case R.id.register_to_login:
                //前往登陆
                Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
                startActivity(intent);
                //把当前页面销毁掉
                RegisterActivity.this.finish();
                break;
            case R.id.type_cous:
                //调用方法
                type_flag = true;
                radioType();

                break;
            case R.id.type_boss:
                //调用方法
                type_flag = false;
                radioType();
                break;
            case R.id.gender_boy:
                //调用方法
                gender_flag = true;
                radioGender();

                break;
            case R.id.gender_girl:
                //调用方法
                gender_flag = false;
                radioGender();
                break;
            case R.id.image_H:
                //选择头像活动页面显示
               selectHImg();
                break;
            case R.id.image_one:
                setSelectImage(0);
                break;
            case R.id.image_two:
                setSelectImage(1);
                break;
            case R.id.image_three:
                setSelectImage(2);
                break;
            case R.id.image_four:
                setSelectImage(3);
                break;
            case R.id.image_five:
                setSelectImage(4);
                break;
            case R.id.image_six:
                setSelectImage(5);
                break;
            case R.id.image_seven:
                setSelectImage(6);
                break;
            case R.id.image_eight:
                setSelectImage(7);
                break;
            case R.id.image_nine:
                setSelectImage(8);
                break;

        }
    }

    //单选框的问题
    //type
    public void radioType(){
        type_cous.setChecked(type_flag);
        type_boss.setChecked(!type_flag);
    }
    //gender
    public void radioGender(){
        gender_boy.setChecked(gender_flag);
        gender_girl.setChecked(!gender_flag);
    }

    //选择图片
    public void selectHImg(){
        //创建对话框实例
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        //获取显示的页面
        View view = View.inflate(this, R.layout.image_select, null);
        //设置页面
        builder.setView(view);

        final AlertDialog dlg = builder.create();
        //初始化相应的内容
        initSelectView(view);

        //取消
        imageJe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dlg.cancel();
            }
        });

        //确认
        imageRe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //等于-1即为没有选择头像
                if(selectNum == -1){
                    selectImage = imageList[0];
                }else{
                    selectImage = imageList[selectNum];
                }
                //之后设置注册页面为该图片
                selectImgBtn.setImageResource(selectImage);
                dlg.dismiss();
            }
        });


        //获取显示的内容
        dlg.show();
    }

    //设置图片背景颜色
    public void setSelectImage(int num){
        selectNum = num;

        for (int i = 0; i <lineData.length; i++){
            lineData[i].setBackgroundColor(Color.parseColor("#ffffff"));
        }

        lineData[num].setBackgroundColor(Color.parseColor("#f5f3e8"));
    }
    //发送数据
    public void sendRegisterHttp(){

        //处理数据判断用户填写数据是否正确
       un =  uname.getText().toString().trim();
       pa =  paw.getText().toString().trim();
       em =  email.getText().toString().trim();

       gender = gender_flag ? "帅哥": "美女";
       type = type_flag ? "普通用户": "商家";
       hImgId = String.valueOf(selectImage);

       if(TextUtils.isEmpty(un)){
           Toast.makeText(this, "用户不能为空", Toast.LENGTH_LONG).show();
           return;
       }

       if(TextUtils.isEmpty(pa)){
           Toast.makeText(this, "密码不能为空", Toast.LENGTH_LONG).show();
           return;
       }

       if(TextUtils.isEmpty(em)){
           Toast.makeText(this, "邮箱不能为空", Toast.LENGTH_LONG).show();
           return;
       }

       if(selectImage == R.drawable.init_h_img){
           Toast.makeText(this, "请选择您的头像", Toast.LENGTH_LONG).show();
           return;
       }





       //否则执行下面的逻辑


       new Thread(new Runnable() {
           @Override
           public void run() {
               try{
                   OkHttpClient client = new OkHttpClient();

                   RequestBody requestBody = new FormBody.Builder()
                           .add("uname", un)
                           .add("paw", pa)
                           .add("email", em)
                           .add("type", type)
                           .add("gender", gender)
                           .add("hImgId", hImgId)
                           .build();

                   Request request = new Request.Builder()
                           .url("http://192.168.43.124:8080/register")
                           .post(requestBody)
                           .build();

                   Response response = client.newCall(request).execute();
                   String string = response.body().string();

                   System.out.println("已经得到数据");
                   //调用函数解析json
                   register(string);
               }catch (Exception e){
                   e.printStackTrace();
                   System.out.println("异常");

               }
           }
       }).start();
   }

   //注册
     public void register(String myId){

        if(myId.equals("0")){

            //在子线程 中不能使用Toast 必须增加下面这两行
            Looper.prepare();
            Toast.makeText(this, "用户名已经存在", Toast.LENGTH_LONG).show();
            Looper.loop();
            return;
        }else if(myId.equals("-1")){

            Looper.prepare();
            Toast.makeText(this, "注册失败请重新操作", Toast.LENGTH_LONG).show();
            Looper.loop();
            //清空数据
            uname.setText("");
            paw.setText("");
            email.setText("");
            return;
        }


        //跳转到首页 并把信息保存到数据库里面  不知为何返回来的数据一双引号
         myId = myId.replaceAll("\""," ").trim();
        //先删除再插入
         LoginSQLManger.getInstance(RegisterActivity.this).deleteAll();
         SQLSavaInfo info = new SQLSavaInfo(un, pa, myId, em, hImgId, type, gender);
        //接下来就是进行增上改查
         //插入数据
         LoginSQLManger.getInstance(RegisterActivity.this).insertInfo(info);

        Intent intent = new Intent(RegisterActivity.this, HomeActivity.class);
        startActivity(intent);

        //销毁当前页面
         RegisterActivity.this.finish();
    }
}
